<template>
  <div class="web-box">
    <div class="operate-bar">
      <div style="display: flex;">
        <el-upload style="margin-right: 10px;" class="upload-demo" ref="uploadRef" :show-file-list="false"
          :auto-upload="false" :before-upload="beforeUpload" :on-change="handleFileUpload" :limit="1"
          :disabled="uploading">
          <el-button :loading="uploading" color="#337ECC" size="small" :disabled="auth * 1 < 3 || uploading">
            <el-tooltip v-if="auth * 1 < 3" content="请联系管理员授权" placement="top">上传</el-tooltip>
            <span v-else> {{ uploading ? '上传中...' : '上传' }}</span>
          </el-button>
        </el-upload>

        <el-button color="#337ECC" size="small" plain :disabled="auth * 1 < 2" @click="download">
          <el-tooltip v-if="auth * 1 < 2" content="请联系管理员授权" placement="top">下载</el-tooltip>
          <span v-else>下载</span>
        </el-button>

        <!-- <el-button color="#337ECC" size="small" plain :disabled="auth < 4">
          <el-tooltip v-if="auth < 4" content="请联系管理员授权" placement="top">删除</el-tooltip>
          <span v-else>删除</span>
        </el-button> -->

        <!-- <el-button color="#337ECC" size="small" plain :disabled="auth < 3">
          <el-tooltip v-if="auth < 3" content="请联系管理员授权" placement="top">
            移动
          </el-tooltip>
        </el-button> -->
      </div>
      <!-- <el-input v-model="filterText" style="width: 200px;" placeholder="请输入" size="small"> <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template></el-input> -->
    </div>
    <div class="cont-table">
      <el-table :data="tableData" border stripe max-height="650px" class="custom-table"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" />
        <template v-for="(item, index) in tabHeading">
          <el-table-column show-overflow-tooltip :prop="item.prop" :label="item.label" :width="item.width"
            :min-width="item.minWidth">
            <!-- 根据文件类型匹配图标 -->
            <template #default="{ row }" v-if="item.prop === 'suffix'">
              <span style="margin-right: 10px;">
                <svg class="icon" aria-hidden="true" v-if="fileType.find(t => t.type === row.suffix)">
                  <use :xlink:href="fileType.find(t => t.type === row.suffix).iconName"></use>
                </svg>
              </span>
              <span>{{ row[item.prop] }}</span> <!-- 文字备用 -->
            </template>
            <template #default="{ row }" v-else-if="item.prop === 'size'">
              <span> {{ formatFileSize(row[item.prop]) }}</span>
            </template>
            <template #default="{ row }" v-else-if="item.prop === 'createtime'">
              <span>{{ date(row[item.prop]) }}</span>
            </template>
            <!-- 其他列直接显示数据 -->
            <template #default="{ row }" v-else>
              {{ row[item.prop] }}
            </template>
          </el-table-column>
        </template>
        <el-table-column fixed="right" label="操作" width="100">
          <template #default="{ row }">
            <el-button link type="primary" size="small" v-if="auth * 1 > 1" @click="getPreview(row)">查看</el-button>
            <!-- <el-button link type="primary" size="small" v-if="auth > 3">授权</el-button> -->
            <!-- <el-button link type="primary" size="small">移动</el-button> -->
            <el-button link type="danger" size="small" v-if="auth * 1 > 3" @click="fileDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <div class="footer_pag">
      <el-pagination v-model:current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" background
        size="small" layout="->,total, prev, pager, next,sizes" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div> -->
  </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import api from "@/api/httpApi.js"
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/api/store'
import { cancelAllPendingRequests } from "@/api/request.js"
import { date } from "@/utils/plugs";

const userStore = useUserStore()
userStore.refreshStore()//强制刷新数据
// 用户信息
const userInfo = computed(() => userStore.userInfo);

const props = defineProps({
  filesList: {
    type: Array,
    default: []
  },
  filesListID: {
    type: String || Number,
    default: "",
  },
  filesListAuth: {
    type: String || Number,
    default: "",
  },
});
const emit = defineEmits(['preview', "refreshList"]);
// const uploadRef = useTemplateRef('uploadRef')

const filterText = ref('')
const auth = ref(1)//权限
const pageSize = ref(20)
const pageSizes = ref([20, 40, 60, 80, 100])
const currentPage = ref()
const total = ref(400)
const selectionArr = ref([])
// 表头配置（tabHeading）
const tabHeading = ref([
  {
    prop: 'filename',
    label: '文件名',
    width: '250px',
    minWidth: '180px'
  },
  {
    prop: 'size',
    label: '文件大小',
    minWidth: '100px'
  },
  {
    prop: 'suffix',
    label: '文件类型',
    minWidth: '100px'
  },
  // {
  //   prop: 'proid',
  //   label: '创建用户',
  //   minWidth: '100px'
  // },
  {
    prop: 'createtime',
    label: '上传时间',
    minWidth: '180px'
  },
]);
// 列表数据
const tableData = ref([])
// 文件类型
const fileType = ref([
  { type: 'colour', iconName: '#icon-file2_colour' },
  { type: 'doc', iconName: '#icon-word' },
  { type: 'docx', iconName: '#icon-word' },
  { type: 'xls', iconName: '#icon-EXCEL' },
  { type: 'xlsx', iconName: '#icon-EXCEL' },
  { type: 'pdf', iconName: '#icon-PDF' },
  { type: 'zip', iconName: '#icon-ZIP' },
  { type: 'rar', iconName: '#icon-RAR' },
  { type: 'txt', iconName: '#icon-TXT' },
  { type: 'jpg', iconName: '#icon-PICTURE' },
  { type: 'png', iconName: '#icon-PICTURE' },
  { type: 'video', iconName: '#icon-VIDEO' },
  { type: 'audio', iconName: '#icon-AUDIO' },
])
const handleCurrentChange = () => { };
const handleSizeChange = () => { };

const uploadRef = ref(null);
const uploading = ref(false);
// 文件上传前校验（格式/大小）
const beforeUpload = (file) => {
  // console.log("文件上传前校验", file);

  const validTypes = ['.pdf', '.docx', '.jpg', '.jpeg', '.png', '.xlsx'];
  const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
  const isAllowedType = validTypes.includes(fileExtension);
  const isLt50M = file.size / 1024 / 1024 < 50;
  // const isLt100M = file.size / 1024 / 1024 < 100;

  if (!isAllowedType) {
    ElMessage.error('仅支持上传 PDF/docx/xlsx/图片 格式文件');
    return false;
  }
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过50MB');
    return false;
  }
  return true;
};
// 查看预览
const getPreview = (row) => {
  // console.log('预览', row);
  // 处理数据结构
  let previewObj = {
    parentId: row.proid,
    filePath: row.path,
    filePathImg: row.path_text,
    type: row.suffix,
    id: row.id,
    label: row.filename,
    loaded: false
  }
  emit("preview", previewObj)
}
// 文件选择后触发上传
const handleFileUpload = async (file) => {
  // console.log("触发上传", file);

  if (!beforeUpload(file.raw)) return;

  uploading.value = true;

  try {
    const formData = new FormData();
    formData.append('files', file.raw);
    formData.append('proid', props.filesListID); // 项目 ID
    formData.append('userid', userInfo.value.id); // 用户 ID

    // console.log('FormData 条目:', [...formData.entries()]);

    // 调用上传接口
    await filesUpload(formData);

    // 上传成功反馈
    ElMessage.success('文件上传成功');
    let parentId = props.filesListID;//获取父ID
    getFilesList(parentId)//刷新当前文件列表
    emit("refreshList", String(parentId))//刷新父组件树形列表
    // 清空上传列表（避免重复上传同一文件）
    uploadRef.value.clearFiles();

  } catch (error) {
    // 上传失败反馈
    console.error('上传失败详情:', error);
    ElMessage.error('文件上传失败，请稍后重试');

  } finally {
    // 无论成功失败都关闭加载状态
    uploading.value = false;
  }

};
// 获取文件列表
const getFilesList = (parentId) => {
  if (userInfo.value?.id && parentId) {
    let obj = {
      proid: parentId,
      userid: userInfo.value.id,
    }
    tableData.value = []
    api.FilesList(obj).then((res) => {
      if (res.status === 1) {
        tableData.value = res.data.fileList
        auth.value = res.data.auth ? res.data.auth : 0
        total.value = res.data.count
      } else {
        // ElMessage.error(res.message);
      }
    })
  }
}
// 多选回调
const handleSelectionChange = (a) => {
  selectionArr.value = a
}
// 文件下载
const download = () => {
  if (selectionArr.value.length > 1) {
    ElMessage.error("一次只能选一个文件下载");
  } else if (selectionArr.value.length == 0) {
    ElMessage.error("请选择需要下载的文件");
  } else {
    const file = selectionArr.value[0];
    const downloadPath = file.path;
    let downloadName = file.filename;
    let downloadType = file.suffix.replace(/^\./, ''); // 去除后缀前的点号
    // 手动补全文件名后缀（如果缺失）
    if (!/\.\w+$/.test(downloadName)) {
      downloadName += `.${downloadType}`;
    }
    api.ResourceFile({ filepath: downloadPath }).then((res) => {
      // console.log("返回文件流", res);
      // 处理文件流响应
      const blob = new Blob([res], { type: `application/${downloadType}` });
      // 创建临时下载链接
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = downloadName; // 设置下载文件名
      // 触发下载
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a); // 移除临时元素

      // 释放内存
      window.URL.revokeObjectURL(url);
    })

  }
}
// 文件上传
const filesUpload = async (formData) => {
  try {
    // 调用上传接口（显式设置 Content-Type）
    const res = await api.FilesUpload(formData);
    // console.log('上传成功响应:', res);
    return res; // 返回响应数据供上层使用
  } catch (error) {
    // 统一错误处理（已在拦截器中提示，此处可选补充）
    console.error('接口请求失败:', error);
    throw error; // 抛出错误以便上层捕获
  }
};
// 将字节转换为友好单位（B/KB/MB）
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'; // 处理 0 字节的情况

  const units = ['B', 'KB', 'MB', 'GB', 'TB']; // 单位数组
  const base = 1024; // 二进制基数（1KB=1024B，1MB=1024KB）
  const index = Math.floor(Math.log(bytes) / Math.log(base)); // 计算单位索引

  // 避免超出数组范围（如超大文件）
  const validIndex = Math.min(index, units.length - 1);

  // 计算转换后的值（保留 2 位小数）
  const value = (bytes / Math.pow(base, validIndex)).toFixed(2);

  return `${value} ${units[validIndex]}`;
};
// 删除
const fileDelete = (row) => {
  ElMessageBox.confirm(
    '确定删除该文件？', '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      let data = {
        userid: userInfo.value.id,
        proid: Number(row.proid),
        fileid: Number(row.id)
      }
      api.FilesDelete(data).then((res) => {
        if (res.status == 1) {
          ElMessage.success(res.message)
          getFilesList(row.proid)//刷新列表
          emit("refreshList", String(row.proid))
        } else {
          ElMessage.error(res.message);
        }

      })
    })
}

// 组件卸载时取消所有未完成请求
onUnmounted(() => {
  // 取消当前页面的所有请求
  // activeRequests.forEach((cancel) => cancel());
  // activeRequests.length = 0;

  // 取消全局所有未完成的请求
  cancelAllPendingRequests();
});
watch(
  () => props.filesListID,
  (newValue, oldValue) => {
    // console.log("[调试]获取最新的子项ID",newValue);

    getFilesList(newValue)
  },
  {
    immediate: true // 立即执行一次
  }
);
watch(() => props.filesListAuth, (newValue, oldValue) => {
  auth.value = newValue
}, {
  immediate: true // 立即执行一次
})
</script>

<style lang="less" scoped>
@import "@/assets/scss/web.scss";
</style>